﻿using Dapper;
using Dapper.Contrib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tauren.Business.DLL.Base;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.DLL.RoleInfoDLL
{
    internal class RoleInfoBusiness : BaseDLL, IRoleInfoBusiness
    {
        public RoleInfoBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {
        }

        public long Add(Roleinfo Model) => this.dbConnection.Insert(Model);

        public bool Add(List<RoleRes> res)
        {
            if (res.Any())
            {
                this.dbConnection.Execute($"delete  from `roleres` where roleid = {res.FirstOrDefault().RoleId};");
                return this.dbConnection.Insert(res) >= 0;
            }
            return true;
        }

        public bool Add(List<RolePersonInfo> PersonInfos, long roleId)
        {
            this.dbConnection.Execute($"delete  from `rolepersoninfo` where roleid = {roleId};");
            if (PersonInfos.Any())
            {
                return this.dbConnection.Insert(PersonInfos) >= 0;
            }
            return true;
        }

        public bool Add(List<RolePermission> Permissions, long roleId)
        {
            this.dbConnection.Execute($"delete  from `rolepermission` where roleid = {roleId};");
            if (Permissions.Any())
            {
                return this.dbConnection.Insert(Permissions) >= 0;
            }
            return true;
        }

        public bool Edit(Roleinfo Model) => this.dbConnection.Update(Model);

        public Roleinfo FirstDefault(long AutoId) => this.dbConnection.Get<Roleinfo>(AutoId);

        public List<RoleInfoTable> Get(long AutoId) =>
            dbConnection.Query<RoleInfoTable>($"select r.autoid ,r.code, r.enable ,r.havesystemrole ,rs.`language` ,rs.value from roleinfo r left join roleres rs on r.autoid =rs.roleid where r.havedelete !=1  and r.autoid={AutoId}").ToList();

        public List<RolePermission_OutPut> GetRolePermissions(long RoleId) => this.dbConnection.Query<RolePermission_OutPut>($"select r.permissionid,p.value from rolepermission r left join permissionres p on p.permissionid =r.permissionid and p.`language` ='{Global.Language}' where roleid =@RoleId", new RolePermission { RoleId = RoleId }).ToList();

        public List<RolePersonInfo_OutPut> GetRolePersonInfos(long RoleId) => this.dbConnection.Query<RolePersonInfo_OutPut>($"select r.empid,e.cnname,e.enname from `rolepersoninfo` r left join employee e  on r.empid =e.empid  where r.roleid={RoleId}").ToList();

        public double GetSeq()
        {
            Roleinfo roleinfo = this.dbConnection.QueryFirstOrDefault<Roleinfo>("SELECT * FROM roleinfo WHERE havedelete=0  ORDER BY autoid DESC LIMIT 0,1");
            if (roleinfo is null) return 1;
            else return (roleinfo.Sequence is null ? 1 : roleinfo.Sequence.Value + 1);
        }

        public bool IsCodeRepeat(long AutoId, string Code)
        {
            string sql = $"SELECT code FROM roleinfo WHERE code='{Code}'";
            if (AutoId != 0)
            {
                sql = $"{sql} AND autoid !={AutoId}";
            }
            return dbConnection.Query<Roleinfo>(sql).Any();
        }

        public List<PageRoleInfoTable> Pages(QueryModel queryModel, out long Total)
        {
            Total = 0;
            string where = "";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"   AND r.code LIKE '%{queryModel.KeyWord}%' OR rs.value LIKE '%{queryModel.KeyWord}%' ";
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "sequence";
                queryModel.IsAsc = false;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            }
            if (queryModel.paramters.Any())
            {
                queryModel.paramters.ForEach(p =>
                {
                    where += $"  and {p.Label} like '%{p.Value}%'  ";
                });
            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"SELECT count(r.AutoId) as cnt FROM roleinfo r LEFT JOIN roleres rs ON r.autoid =rs.roleid  
                          AND rs.`language` = '{this.Global.Language}'  WHERE r.havedelete !=1
                        {where}  ;");
            sql.Append(@$"SELECT  r.autoid ,r.code, r.enable ,r.havesystemrole ,rs.`language` ,rs.value,r.creator ,r.creatdate ,r.modifier ,r.modifdate 
                          FROM roleinfo r LEFT JOIN roleres rs ON r.autoid =rs.roleid  
                          AND rs.`language` = '{this.Global.Language}' WHERE r.havedelete !=1
                        {where}  ORDER BY {queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{ queryModel.PageSize} ;");
            using (var reader = dbConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PageRoleInfoTable> pageModules = reader.Read<PageRoleInfoTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                });
                return pageModules;
            }
        }
    }
}
